﻿/* Write a program, that reads from the console an array of N integers and an integer K, sorts the array and using the method 
 * Array.BinSearch() finds the largest number in the array which is ≤ K.
 */




using System;

class SortBinSearch
{
    static void Main()
    {
        uint N;
        int K;

        bool iProvided = false;
        do
        {
            if (iProvided == true) Console.WriteLine("Error: invalid input! Please enter a positive integer.\r\n\t* Valid input: N > 0");
            else iProvided = true;
            Console.Write("Enter N: ");
        } while (UInt32.TryParse(Console.ReadLine(), out N) == false || N < 1);

        iProvided = false; //reset iProvided
        do
        {
            if (iProvided == true) Console.WriteLine("Error: invalid input! Please enter an integer.\r\n\t* Valid input: {0} to {1}", Int32.MinValue, Int32.MaxValue);
            else iProvided = true;
            Console.Write("Enter K: ");
        } while (Int32.TryParse(Console.ReadLine(), out K) == false);


        int[] nums = new int[N];
        for (int i = 0; i < nums.Length; i++)
        {
            iProvided = false; //reset iProvided to avoid getting the error message on valid input
            do
            {
                if (iProvided == true) Console.WriteLine("Error: invalid input! Please enter an integer.\r\n\t* Valid input: {0} to {1}", Int32.MinValue, Int32.MaxValue);
                else iProvided = true;
                Console.Write("Enter array element #{0}: ", i+1);
            } while (Int32.TryParse(Console.ReadLine(), out nums[i]) == false);
            //Console.WriteLine(nums[i]);
        }

        //print array
        foreach (int var in nums) Console.WriteLine(var);
        Console.WriteLine();
        
        //print sorted
        Console.WriteLine("Sorted: ");
        Array.Sort(nums);
        foreach (int var in nums) Console.WriteLine(var);
        Console.WriteLine();

        if (nums[0] <= K)
        {
            //searching for the number
            int lk = Array.BinarySearch(nums, K);
            if (lk >= 0)
            {
                Console.WriteLine("K was found!\r\nIndex: {0}, Actual number: {1}", lk, nums[lk]);
            }
            else
            {
                Console.WriteLine("K was not found, but we found the closest one!\r\nIndex: {0}, Actual number: {1}", -lk - 2, nums[-lk - 2]);
            }
        }
        else
            Console.WriteLine("There isn't any number in the array which is <= {0}", K);
    }
}
